package com.dgut.springsecurity.Adapter;

import com.dgut.springsecurity.Details.AdminDetailService;
import com.dgut.springsecurity.handler.AdminLoginFailureHandler;
import com.dgut.springsecurity.handler.AdminLoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Configuration
public class AdministrationAdapter extends WebSecurityConfigurerAdapter {

    @Resource
    private AdminDetailService adminDetailService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private AdminLoginSuccessHandler adminLoginSuccessHandler;
    @Resource
    private AdminLoginFailureHandler adminLoginFailureHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(adminDetailService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**","/css/**", "/img/**", "/**/*.png","/fonts/**","/h-ui/**","/h-ui.admin/**","/images/**","/js/**","/lib/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                // 配置安全过滤链只拦载检查 '/admin/**' 的请求，并配置需要的权限。
                .antMatcher("/admin/**")
                .authorizeRequests().anyRequest().hasAnyAuthority("ADMIN").and()
                // 自定义登录界面
                .formLogin()
                .loginPage("/admin/login_backend").permitAll()
                .loginProcessingUrl("/admin/login_backend").permitAll()
                // 设置默认身份认证成功后跳转的页面,即直接访问登录界面时，认证成功后跳转的页面。
                //.defaultSuccessUrl("/admin")
                .successHandler(adminLoginSuccessHandler)
                .failureHandler(adminLoginFailureHandler).and()
                // 自定义退出登录请求Url、成功退出登录后的重定向Url
                .logout()
                .logoutUrl("/admin/logout").permitAll()
                .logoutSuccessUrl("/admin/login_backend?logout");
    }
}
